/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.PropertyEntity;
import com.je.bpm.engine.impl.persistence.entity.PropertyEntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class ValidateExecutionRelatedEntityCountCfgCmd implements Command<Void> {

    private static final Logger logger = LoggerFactory.getLogger(ValidateExecutionRelatedEntityCountCfgCmd.class);

    public static String PROPERTY_EXECUTION_RELATED_ENTITY_COUNT = "cfg.execution-related-entities-count";

    @Override
    public Void execute(CommandContext commandContext) {

        /*
         * If execution related entity counting is on in config | Current property in database : Result
         *
         *  A) true | not there : write new property with value 'true'
         *  B) true | true : all good
         *  C) true | false : the feature was disabled before, but it is enabled now. Old executions will have a local flag with false.
         *                    It is now enabled. This is fine, will be handled in logic. Update the property.
         *
         *  D) false | not there: write new property with value 'false'
         *  E) false | true : the feature was disabled before and enabled now. To guarantee data consistency, we need to remove the flag from all executions.
         *                    Update the property.
         *  F) false | false : all good
         *
         * In case A and D (not there), the property needs to be written to the db
         * Only in case E something needs to be done explicitely, the others are okay.
         */

        PropertyEntityManager propertyEntityManager = commandContext.getPropertyEntityManager();

        boolean configProperty = commandContext.getProcessEngineConfiguration().getPerformanceSettings().isEnableExecutionRelationshipCounts();
        PropertyEntity propertyEntity = propertyEntityManager.findById(PROPERTY_EXECUTION_RELATED_ENTITY_COUNT);

        if (propertyEntity == null) {
            // 'not there' case in the table above: easy, simply insert the value
            PropertyEntity newPropertyEntity = propertyEntityManager.create();
            newPropertyEntity.setName(PROPERTY_EXECUTION_RELATED_ENTITY_COUNT);
            newPropertyEntity.setValue(Boolean.toString(configProperty));
            propertyEntityManager.insert(newPropertyEntity);

        } else {
            boolean propertyValue = Boolean.valueOf(propertyEntity.getValue().toString().toLowerCase());
            if (!configProperty && propertyValue) {
                if (logger.isInfoEnabled()) {
                    logger.info("Configuration change: execution related entity counting feature was enabled before, but now disabled. "
                            + "Updating all execution entities.");
                }
                commandContext.getProcessEngineConfiguration().getExecutionDataManager().updateAllExecutionRelatedEntityCountFlags(configProperty);
            }
            // Update property
            if (configProperty != propertyValue) {
                propertyEntity.setValue(Boolean.toString(configProperty));
                propertyEntityManager.update(propertyEntity);
            }

        }

        return null;
    }

}
